package org.example.utils;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

//2.把wav文件进行切割
//按声音最高点进行切割
public class AudioVolumeAnalyzer {

//    public static void main(String[] args) {
//        String inputFilePath = "D:\\heima-java\\ssm\\01-spring\\day02\\代码\\spring\\demo23232\\hm-dianping\\upload\\voice\\2024\\12\\06/12月6日 下午5点54分.wav"; // 替换为实际文件路径
//        String ffmpegPath = "E:\\java-work-xiangguang\\ffm\\ffmpeg-7.1-essentials_build\\bin\\ffmpeg.exe"; // 替换为实际ffmpeg路径
//
//        try {
//            float maxVolumeTimestamp = analyzeAudioVolume(inputFilePath);
//            // 根据最大音量时间切割音频
////            splitAudioFile(inputFilePath, ffmpegPath, maxVolumeTimestamp);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public  float analyzeAudioVolume(String inputFilePath) throws UnsupportedAudioFileException, IOException {
        File audioFile = new File(inputFilePath);
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile);
        AudioFormat format = audioInputStream.getFormat();
        byte[] audioBytes = audioInputStream.readAllBytes();
        int bytesPerFrame = format.getFrameSize();
        int numFrames = audioBytes.length / bytesPerFrame;

        float maxVolume = 0;
        long maxVolumeTimestamp = 0;

        for (int i = 0; i < numFrames; i++) {
            int sampleIndex = i * bytesPerFrame;
            float frameVolume = 0;

            if (bytesPerFrame == 2) {
                short sample = (short) ((audioBytes[sampleIndex + 1] << 8) | (audioBytes[sampleIndex] & 0xFF));
                frameVolume = Math.abs(sample) / 32768.0f;
            } else if (bytesPerFrame == 4) {
                short sampleLeft = (short) ((audioBytes[sampleIndex + 1] << 8) | (audioBytes[sampleIndex] & 0xFF));
                short sampleRight = (short) ((audioBytes[sampleIndex + 3] << 8) | (audioBytes[sampleIndex + 2] & 0xFF));
                frameVolume = (Math.abs(sampleLeft) + Math.abs(sampleRight)) / (2 * 32768.0f);
            }

            if (frameVolume > maxVolume) {
                maxVolume = frameVolume;
                maxVolumeTimestamp = i;
            }
        }

        float durationInSeconds = maxVolumeTimestamp / (float) audioInputStream.getFormat().getFrameRate();
        System.out.println("最大音量发生的时间: " + durationInSeconds + " 秒");
        return durationInSeconds;
    }

    public  void splitAudioFile(String inputFilePath, String ffmpegPath, float splitTimeInSeconds,String outputFile1,String outputFile2) throws IOException {
//        String outputFile1 = "D:\\heima-java\\ssm\\01-spring\\day02\\代码\\spring\\demo23232\\hm-dianping\\upload\\voice\\2024\\12\\06/wp1.wav";
//        String outputFile2 = "D:\\heima-java\\ssm\\01-spring\\day02\\代码\\spring\\demo23232\\hm-dianping\\upload\\voice\\2024\\12\\06/wp2.wav";

        // 命令1: 从 0 到 splitTimeInSeconds 切割
        String command1 = String.format("\"%s\" -i \"%s\" -t %f \"%s\"", ffmpegPath, inputFilePath, splitTimeInSeconds, outputFile1);

        // 命令2: 从 splitTimeInSeconds 到结束切割
        String command2 = String.format("\"%s\" -i \"%s\" -ss %f \"%s\"", ffmpegPath, inputFilePath, splitTimeInSeconds, outputFile2);

        // 执行命令1
        executeCommand(command1);
        // 执行命令2
        executeCommand(command2);
    }

    public  void executeCommand(String command) throws IOException {
        Process process = Runtime.getRuntime().exec(command);

        // 获取错误流输出
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String line;
        while ((line = errorReader.readLine()) != null) {
            System.out.println("ERROR: " + line);
        }

        // 等待命令执行完成
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //有bug,它处理的文件不是outputFilePath变成了其他
    public List<Object> qiege(String ffmpegPath,File qiegeUrl,String uuidString,long number,String outputFilePath) {
        String outputFile1 = qiegeUrl + "/" + uuidString + number + ".wav";
        number++;
        String outputFile2 = qiegeUrl + "/" + uuidString + number + ".wav";
        number++;
        System.out.println("第三点第一个切割完成" + outputFile1 + "     " + outputFile2);
        try {
            AudioVolumeAnalyzer audioVolumeAnalyzer2 = new AudioVolumeAnalyzer();
            float maxVolumeTimestamp = audioVolumeAnalyzer2.analyzeAudioVolume(outputFilePath);      //传入的参数outputFilePath为实际的完整的原wav路径
            // 根据最大音量时间切割音频
            audioVolumeAnalyzer2.splitAudioFile(outputFilePath, ffmpegPath, maxVolumeTimestamp, outputFile1, outputFile2);

            return List.of(outputFile1,outputFile2,number);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
